package com.inmaytide.website.utils;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 通过Java的Zip输入输出流实现压缩和解压文件
 *
 * @author liujiduo
 */
public final class ZipUtil {

    private ZipUtil() {
    }

    /**
     * 压缩文件
     *
     * @param filePath 待压缩的文件路径
     * @return 压缩后的文件
     */
    public static File zip(String filePath) {
        File target = null;
        File source = new File(filePath);
        if (source.exists()) {
            // 压缩文件名=源文件名.zip
            String zipName = source.getName() + ".zip";
            target = new File(source.getParent(), zipName);
            if (target.exists()) {
                target.delete(); // 删除旧的文件
            }
            FileOutputStream fos = null;
            ZipOutputStream zos = null;
            try {
                fos = new FileOutputStream(target);
                zos = new ZipOutputStream(new BufferedOutputStream(fos));
                // 添加对应的文件Entry
                addEntry("/", source, zos);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                closeQuietly(zos, fos);
            }
        }
        return target;
    }

    /**
     * 扫描添加文件Entry
     *
     * @param base   基路径
     * @param source 源文件
     * @param zos    Zip文件输出流
     * @throws IOException
     */
    private static void addEntry(String base, File source, ZipOutputStream zos)
            throws IOException {
        // 按目录分级，形如：/aaa/bbb.txt
        String entry = base + source.getName();
        if (source.isDirectory()) {
            for (File file : source.listFiles()) {
                // 递归列出目录下的所有文件，添加文件Entry
                addEntry(entry + "/", file, zos);
            }
        } else {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                byte[] buffer = new byte[1024 * 10];
                fis = new FileInputStream(source);
                bis = new BufferedInputStream(fis, buffer.length);
                int read = 0;
                zos.putNextEntry(new ZipEntry(entry));
                while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, read);
                }
                zos.closeEntry();
            } finally {
                closeQuietly(bis, fis);
            }
        }
    }

    /**
     * 解压文件
     *
     * @param sourceFile
     * @param targetDir
     */
    public static void unzip(File sourceFile, String targetDir) {
        if (!sourceFile.exists() || sourceFile.isDirectory() || !sourceFile.canRead()) {
            return;
        }

        ZipInputStream zis = null;
        BufferedOutputStream bos = null;
        try {
            InputStream is = new FileInputStream(sourceFile);
            unzip(is, targetDir);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeQuietly(zis, bos);
        }
    }

    /**
     * 读取解压文件
     *
     * @param is
     */
    public static List<ZipEntry> readZip(InputStream is) {
        ZipInputStream zis = null;
        List<ZipEntry> result = new ArrayList<ZipEntry>();
        try {
            if (is == null)
                throw new IOException("压缩包流为空！");

            zis = new ZipInputStream(is, Charset.forName("GBK"));
            ZipEntry entry = null;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory())
                    continue;

                result.add(entry);
            }
            zis.closeEntry();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            closeQuietly(zis);
            return result;
        }
    }

    /**
     * 解压文件
     *
     * @param is
     * @param targetDir
     */
    public static List<File> unzip(InputStream is, String targetDir) {
        List<File> result = new ArrayList<>();
        ZipInputStream zis = new ZipInputStream(is);
        try {
            List<ZipEntry> entrys = readZip(is);
            for (ZipEntry entry : entrys) {
                if (entry.isDirectory())
                    continue;

                File target = new File(targetDir, entry.getName());
                if (!target.getParentFile().exists()) {
                    // 创建文件父目录
                    target.getParentFile().mkdirs();
                }
                // 文件复制
                int flag = IOUtils.copy(zis, new FileOutputStream(target));
                if (flag == -1) {
                    throw new IOException("解压文件出错！");
                }
                result.add(target);
            }
            zis.closeEntry();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            closeQuietly(zis);
            return result;
        }
    }

    /**
     * 关闭一个或多个流对象
     *
     * @param closeables 可关闭的流对象列表
     * @throws IOException
     */
    public static void close(Closeable... closeables) throws IOException {
        if (closeables != null) {
            for (Closeable closeable : closeables) {
                if (closeable != null)
                    closeable.close();
            }
        }
    }

    /**
     * 关闭一个或多个流对象
     *
     * @param closeables 可关闭的流对象列表
     */
    public static void closeQuietly(Closeable... closeables) {
        try {
            close(closeables);
        } catch (IOException e) {
            // do nothing
        }
    }

    public static void main(String[] args) {
        String targetPath = "E:\\Win7壁纸";
        File file = ZipUtil.zip(targetPath);
        System.out.println(file);
        ZipUtil.unzip(new File("F:\\Win7壁纸.zip"), "D:\\");
    }

}